package top.zackyoung.bbs.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.zackyoung.bbs.entity.FileResult;
import top.zackyoung.bbs.entity.User;
import top.zackyoung.bbs.service.HdfsService;
import top.zackyoung.bbs.service.UserService;
import top.zackyoung.bbs.utils.PicUtil;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: ZackYoung
 * @time: 2020/6/8
 */
@Controller
public class FileController {
    @Autowired
    private UserService userService;


    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "uploadImage", method = RequestMethod.POST)
    @ResponseBody
    public FileResult uploadImage(HttpServletRequest req, @RequestParam("file") MultipartFile file) throws Exception {
        User user = userList(req);
        if (user == null) {
            return new FileResult(false, "请登录账号");
        }
        if (StringUtils.isEmpty(file.getName())) {
            return new FileResult(false, "文件名错误");
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!(PicUtil.IMG_TYPE_DMG.equals(suffix.toUpperCase()) ||
                PicUtil.IMG_TYPE_GIF.equals(suffix.toUpperCase()) ||
                PicUtil.IMG_TYPE_JPEG.equals(suffix.toUpperCase()) ||
                PicUtil.IMG_TYPE_JPG.equals(suffix.toUpperCase()) ||
                PicUtil.IMG_TYPE_PNG.equals(suffix.toUpperCase()) ||
                PicUtil.IMG_TYPE_SVG.equals(suffix.toUpperCase()))) {
            return new FileResult(false, "文件格式必须为图片");
        }

        String filePath = HdfsService.uploadImage(file, user.getUsername());
        return new FileResult("/readImg" + filePath, "成功");
    }


    @Resource
    private HttpServletResponse response;

    /**
     * 读取HDFS头像
     *
     * @param username
     * @param imgPath
     * @throws Exception
     */
    @RequestMapping(value = "/readImg/user/{username}/{imgPath}")
    @ResponseBody
    public void readImg(@PathVariable("username") String username, @PathVariable("imgPath") String imgPath) throws Exception {
        OutputStream os = null;
        try {
            response.setContentType("image/jpeg");
            os = response.getOutputStream();
            if (HdfsService.enable) {
                //        读取图片
                String path = "/user/" + username + "/" + imgPath;
                boolean existFile = HdfsService.existFile(path);
                if (existFile == false) {
                    HdfsService.noImg(os);
                } else if (imgPath.contains("avatar_")) {
                    BufferedImage image = HdfsService.readAvatar(path);
                    ImageIO.write(image, "jpg", os);
                } else {
                    HdfsService.readImg(path, response);
                }
            } else {
                BufferedImage image = HdfsService.readAvatar(imgPath);
                ImageIO.write(image, "jpg", os);
            }
        } catch (IOException e) {
            System.out.println("获取图片异常{}" + e.getMessage());
        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }


    }

    @RequestMapping(value = "/user/control/updateAvatar", method = RequestMethod.POST)
    @ResponseBody
    public Map upload(@RequestParam("file") MultipartFile file, HttpServletRequest request)
            throws IllegalStateException, IOException {
        Map<String, String> error = new HashMap<String, String>();//错误

        String _width = request.getParameter("width");
        String _height = request.getParameter("height");
        String _x = request.getParameter("x");
        String _y = request.getParameter("y");


        // 判断文件是否为空，空则返回失败页面
        if (file.isEmpty()) {
            error.put("success", "false");
            return error;
        }

        // 数据库修改
        User user = (User) request.getSession().getAttribute("userList");
        try {
            String filePath = HdfsService.uploadAvatar(file, user.getUsername(), _width, _height, _x, _y, error);
            int result = userService.updateAvatar(filePath, user.getId());
            if (result > 0) {
                user.setAvatarname(filePath);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return error;
    }

    User userList(HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("userList");
        return user;
    }

}
